#!/usr/bin/env bash

REL_SCRIPT_DIR="`dirname \"$0\"`"
SCRIPT_DIR="`( cd \"$REL_SCRIPT_DIR\" && pwd )`"
PROJECT_ROOT="`( cd \"$SCRIPT_DIR/..\" && pwd )`"

case "$OSTYPE" in
    darwin*) PLATFORM="OSX" ;;
    linux*)  PLATFORM="LINUX" ;;
    bsd*)    PLATFORM="BSD" ;;
    *)       PLATFORM="UNKNOWN" ;;
esac

sedi() {
    if [[ "$PLATFORM" == "OSX" || "$PLATFORM" == "BSD" ]]; then
        sed -i "" "$@"
    elif [ "$PLATFORM" == "LINUX" ]; then
        sed -i "$@"
    else
        exit 1
    fi
}

# `set-jep-status <jep-number> <status>`
if [ -z "$1" ] ; then
  echo "Missing JEP number." >&2
  echo "Usage: $0 <jep-number> <status>" >&2
  exit 1
fi

if [ -z "$2" ] ; then
  echo "Missing JEP status." >&2
  echo "Usage: $0 <jep-number> <status>" >&2
  exit 1
fi

JEP_NUMBER=$1
JEP_README="$PROJECT_ROOT/jep/$JEP_NUMBER/README.adoc"

if [ ! -f $JEP_README ] ; then
  echo Could not find $JEP_NUMBER/README.adoc.
  exit 1
fi

JEP_STATUS=$(sed -n '/| Status/,/|/p' $JEP_README | head -n 2 | tail -n 1)

JEP_NEW_STATUS="$(grep -i -e "^| $2" <<EOF
| Draft :speech_balloon:
| Deferred :hourglass:
| Accepted :ok_hand:
| Rejected :no_entry:
| Withdrawn :hand:
| Final :lock:
| Replaced :dagger:
| Active :smile:
EOF
)"

if [ -z "$JEP_NEW_STATUS" ] ; then
  echo Invalid JEP status: $2.
  exit 1
fi

# This will replace other lines with the same content as the status line
# So far this is only a problem on JEP-1 which we shouldn't have to set status on

sedi "s/^$JEP_STATUS/$JEP_NEW_STATUS/" $JEP_README &&
    echo "Set status of JEP-$JEP_NUMBER to $(echo $JEP_NEW_STATUS | cut -d " " -f 2)." &&
    $SCRIPT_DIR/enumerate-jeps
